package com.xdhl.fu.fi.rocketmq;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * 消息生产者
 *
 * @author 朱力维
 * @time 2022/6/10 20:58
 */
@Component
public class MsgProducer {

    private static final Logger log = LoggerFactory.getLogger(MsgProducer.class);

    @Value("#{'${spring.application.name}'+'-'+'${spring.profiles.active}'}")
    private String producerGroup;

    @Value("${fu.rocketmq.namesrv-addr}")
    private String namesrvAddr;

    private DefaultMQProducer mqProducer;

    //调用方注入MsgProducer后 通过这个方法获取配置好的DefaultMQProducer
    public DefaultMQProducer getMqProducer() {
        return mqProducer;
    }

    @PostConstruct
    public void initMQ() {
        mqProducer = new DefaultMQProducer(producerGroup);
        mqProducer.setNamesrvAddr(namesrvAddr);
        mqProducer.setVipChannelEnabled(false);
        try {
            mqProducer.start();
            log.info("消息生产者启动成功。");
        } catch (MQClientException e) {
            log.error(e.getMessage());
        }
    }

    @PreDestroy
    public void destory() {
        mqProducer.shutdown();
    }
}
